package com.example.wlzz.utils;
import com.example.wlzz.api.ConfigAPI;
import com.example.wlzz.api.FileApi;
import com.example.wlzz.config.BeansConfig;
import com.example.wlzz.tencentAI.api.TencentAPI;
import com.example.wlzz.tencentAI.sign.TencentAISign;
import com.example.wlzz.tencentAI.sign.TencentAISignSort;
import com.example.wlzz.vo.CodeVO;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class CodeRequestUtil {

    public static CodeVO codeRequest(String codeUrl, Map<String,String> map,String domainName)throws Exception{
        FileApi fileApi = BeansConfig.getBean(FileApi.class);
        //    http://211.64.240.25/jxd/verifycode.servlet
        URL url = new URL(codeUrl);  //返回的是4位验证码的图片
        String randomString = KeyUtil.genUniqueKey();
     //  String fileName = "C:\\code\\"+randomString+".jpg";
        String fileName = fileApi.getSave_url()+randomString+".jpg";
        File outFile = new File(fileName);
        OutputStream os = new FileOutputStream(outFile);
        HttpURLConnection urlCon= (HttpURLConnection)url.openConnection();
        String cookie = "JSESSIONID="+map.get("JSESSIONID");
        System.out.println(cookie);
        urlCon.addRequestProperty("Cookie",cookie);
        InputStream is = urlCon.getInputStream();
        byte[] buff = new byte[1024];
        while(true) {    //要注意这种写法
            int readed = is.read(buff);
            if(readed == -1) {
                break;
            }
            byte[] temp = new byte[readed];
            System.arraycopy(buff, 0, temp, 0, readed);   // 这句是关键  <br data-filtered="filtered">
            os.write(temp);
        }
        is.close();
        os.close();
       // String code  = recogntionCode(UrlMethodUtil.local2byte(fileName));
        CodeVO codeVO = new CodeVO();
        codeVO.setCode("");
        codeVO.setCodeImgUrl("http://"+domainName+"/wlzzUser/"+"getCode?number="+randomString);
        codeVO.setCookies(cookie);
//        System.out.println(codeVO);
        return codeVO;
    }
    public static String recogntionCode(byte[] file){  //识别验证码,通用识别
        try {
            //时间戳
            String time_stamp = System.currentTimeMillis() / 1000 + "";
            String img64 = Base64Util.encode(file);
            //随机字符串
            String nonce_str = TencentAISign.getRandomString(10);
            Map<String, String> body = new HashMap<>();   //【接口属性】（注意修改成自己要的参数）
            body.put("app_id", String.valueOf(TencentAPI.APP_ID_AI));
            body.put("time_stamp", time_stamp);
            body.put("nonce_str", nonce_str);
            body.put("image", img64);
            String sign = TencentAISignSort.getSignature(body);
            body.put("sign", sign);
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            HttpResponse responseBD;
            responseBD = HttpsUtil4Tencent.doPostTencentAI(TencentAPI.OCR_GENERAL, headers, body);
            String result = EntityUtils.toString(responseBD.getEntity());
            JSONParser parser = new JSONParser();
            JSONObject simple_json = (JSONObject) parser.parse(result);
            String data = simple_json.get("data").toString();
            JSONObject data_json = (JSONObject) parser.parse(data);
            String item_list = data_json.get("item_list").toString();
            JSONArray itemList_json = (JSONArray) parser.parse(item_list);
            JSONObject item = (JSONObject) parser.parse(itemList_json.get(0).toString());
            String endResult = item.get("itemstring").toString();
            return endResult.replace(" ", "");
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
